class ItemOption < ActiveRecord::Base
  has_many                  :itemizations
  has_many                  :items, :through => :itemizations
  belongs_to                :price_list
  validates_presence_of     :name
  validates_presence_of     :cost
  validates_numericality_of :cost
  validate                  :must_be_for_either_photo_or_video
  validate                  :must_not_be_for_both_a_photo_and_video
  
  after_destroy             :ensure_atleast_one_video_option_persists
  after_destroy             :destroy_dependents
  after_update              :destroy_dependents
  
  def must_be_for_either_photo_or_video
    self.errors.add("An item option must be for either a photo or a video") unless self.for_photo or self.for_video
  end
  
  def must_not_be_for_both_a_photo_and_video
    self.errors.add("An item option must be for either a photo or a video, not both") if self.for_photo and self.for_video
  end
  
protected
  def destroy_dependents
    self.itemizations.each {|itemization| itemization.destroy} unless self.itemizations.empty?
  end
  def ensure_atleast_one_video_option_persists
    ItemOption.create!(:for_video => true, :name => "Digital Download", :cost => "10") if ItemOption.find(:all, :conditions => ['for_video = ?', true]).empty?
  end
end
